package com.wlj.rabbit.produce;

import com.wlj.rabbit.entity.Message;
import com.wlj.rabbit.util.ResultCodeEumn;
import com.wlj.rabbit.util.ResultEntity;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName MessageSender
 * @Description TODO
 * @Author wlj
 * @Date 2018/11/14  14:15
 * @Version 1.0
 */
@Component
public class MessageSender implements RabbitTemplate.ConfirmCallback{

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     *
     * @param exchangeName 交换机名
     * @param routingKey  key
     * @param message 消息对象
     * @return
     */
    public ResultEntity send(String exchangeName,String routingKey,Message message){
        CorrelationData correlationData=new CorrelationData();
        correlationData.setId(message.getId());
        //correlationData消息唯一id
        rabbitTemplate.convertAndSend(exchangeName,routingKey,message,correlationData);
        return new ResultEntity(true,ResultCodeEumn.SUCCESS,message.getId());
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        System.out.println(" 回调id:" + correlationData);
        if (ack) {
            System.out.println("消息成功消费");
        } else {
            System.out.println("消息消费失败:" + cause);
        }
    }
}
